<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="需求日期" prop="reqDate">
        <el-date-picker clearable
                        v-model="queryParams.reqDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择需求日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="单据阶段" prop="docStage">
        <el-select v-model="queryParams.docStage" placeholder="请选择">
          <el-option
            v-for="item in docStageArr"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="审批结果" prop="approvalResult" v-show="isSearchMore">
        <el-select v-model="queryParams.approvalResult" placeholder="请选择">
          <el-option
            v-for="item in approvalResultArr"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否生效" prop="isEffect" v-show="isSearchMore">
        <el-select v-model="queryParams.isEffect" placeholder="请选择">
          <el-option
            v-for="item in isEffectArr"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否关闭" prop="isClose" v-show="isSearchMore">
        <el-select v-model="queryParams.isClose" placeholder="请选择">
          <el-option
            v-for="item in isEffectArr"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否作废" prop="isCancel" v-show="isSearchMore">
        <el-select v-model="queryParams.isCancel" placeholder="请选择">
          <el-option
            v-for="item in isEffectArr"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="text" size="mini" @click="isSearchMore = !isSearchMore">
          <span v-if="isSearchMore">收起</span>
          <span v-else>更多</span>
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['caigou:buyReq:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['caigou:buyReq:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['caigou:buyReq:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['caigou:buyReq:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="buyReqList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
<!--      <el-table-column label="主键id" align="center" prop="id"/>-->
<!--      <el-table-column label="序号" align="center">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ scope.$index+1 }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="单据编号" width="180" align="center" fixed>
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">{{ scope.row.code }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="需求人" align="center" prop="reqUserName"/>
      <el-table-column width="180" label="需求部门" align="center" prop="reqUserDept"/>
      <el-table-column label="需求日期" align="center" prop="reqDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reqDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据阶段" align="center" prop="docStage">
        <template slot-scope="scope">
          <span v-for="doc in docStageArr">
            <template v-if="doc.value == scope.row.docStage">
                {{ doc.label }}
            </template>
            <template v-else></template>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="审批结果" align="center" prop="approvalResult">
        <template slot-scope="scope">
          <span v-for="doc in approvalResultArr">
            <template v-if="doc.value == scope.row.approvalResult">
                {{ doc.label }}
            </template>
            <template v-else></template>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="是否生效" align="center" prop="isEffect">
        <template slot-scope="scope">
          <span v-if="scope.row.isEffect == 0 || scope.row.isEffect == undefined || scope.row.isEffect == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否关闭" align="center" prop="isClose">
        <template slot-scope="scope">
          <span v-if="scope.row.isClose == 0 || scope.row.isClose == undefined || scope.row.isClose == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否作废" align="center" prop="isCancel">
        <template slot-scope="scope">
          <span v-if="scope.row.isCancel == 0 || scope.row.isCancel == undefined || scope.row.isCancel == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="modifyBy"/>
      <el-table-column label="修改时间" align="center" prop="modifyDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifyDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="是否删除" align="center" prop="isDel"/>-->
      <el-table-column width="200" label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleShenghe(scope.row)"
            v-hasPermi="['caigou:buyReq:edit']"
            :disabled="scope.row.approvalResult != 0"
          >审核
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['caigou:buyReq:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['caigou:buyReq:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="1300px" append-to-body>
      <el-form :inline="true" ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单据编号" prop="code">
          <el-input v-model="form.code" readonly placeholder="单据编号"/>
        </el-form-item>
        <el-form-item label="需求人" prop="reqUserId">
          <el-input style="width: auto" v-model="form.reqUserName" readonly placeholder="请选需求人"/>
          <el-button plain @click="userDialogVisible = true" :disabled="formOpr != 1">选择用户</el-button>
          <el-dialog
            width="1200px"
            title="根据部门选择用户"
            :visible.sync="userDialogVisible"
            append-to-body>
            <SelectUser @selectUserMethod="changeHandleUser"/>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="userDialogVisible = false">确 定</el-button>
              <el-button @click="userDialogVisible = false">取 消</el-button>
            </div>
          </el-dialog>
        </el-form-item>

        <el-form-item label="需求部门">
          <el-input v-model="form.reqUserDept" readonly placeholder="需求部门"/>
        </el-form-item>
        <el-form-item label="需求日期" prop="reqDate">
          <el-date-picker clearable
                          v-model="form.reqDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择需求日期"
                          :readonly="formOpr!=1"
          >
          </el-date-picker>
        </el-form-item>
        <el-button type="text" @click="isMore = !isMore">
          <span v-if="isMore">收起</span>
          <span v-else>更多</span>
        </el-button>
        <div v-show="isMore">
          <el-form-item label="单据阶段" prop="docStage">
            <el-input :readonly="1==1" v-model="form.docStage"
                      placeholder="单据阶段"/>
          </el-form-item>
          <el-form-item label="审批结果" prop="approvalResult">
            <el-input :readonly="formOpr!=1" v-model="form.approvalResult" placeholder="" readonly/>
          </el-form-item>
          <el-form-item label="是否生效" prop="isEffect">
            <el-input :readonly="1==1" v-model="form.isEffect" placeholder="是否生效"/>
          </el-form-item>
          <el-form-item label="是否关闭" prop="isClose">
            <el-input :readonly="1==1" v-model="form.isClose" placeholder="是否关闭"/>
          </el-form-item>
          <el-form-item label="是否作废" prop="isCancel">
            <el-input :readonly="1==1" v-model="form.isCancel" placeholder="是否作废"/>
          </el-form-item>
          <el-form-item label="创建时间" prop="createDate">
            <el-date-picker clearable
                            v-model="form.createDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="创建时间"
                            :readonly="1==1">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="修改人" prop="modifyBy">
            <el-input v-model="form.modifyBy" :readonly="1==1" placeholder="修改人"/>
          </el-form-item>
          <el-form-item label="修改时间" :readonly="1==1" prop="modifyDate">
            <el-date-picker clearable
                            v-model="form.modifyDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="修改时间"
                            :readonly="1==1">
            </el-date-picker>
          </el-form-item>


        </div>

      </el-form>

      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="销售订单" name="first">销售订单</el-tab-pane>
        <el-tab-pane label="明细" name="second">
          <GoodsSelect :goodsList="goodsArr" :idAndNumberArr="idAndNumberArr" :formOpr="formOpr"
                       @selectGoodsMethod="changeHandleGoods"/>
        </el-tab-pane>

      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="formOpr != 3" type="primary" @click="submitForm">确 定</el-button>
        <el-button v-show="formOpr == 3" type="warning" @click="">审核</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SelectUser from './UserSelect.vue'
import {
  listBuyReq,
  getBuyReq,
  delBuyReq,
  addBuyReq,
  updateBuyReq,
  addBuyReqPlus,
  getBuyReqPlus, updateBuyReqPlus, delBuyReqPlus
} from "@/api/caigou/buyReq";

import GoodsSelect from './GoodsSelect.vue'

export default {
  name: "BuyReq",
  components: {SelectUser, GoodsSelect},
  data() {
    return {
      formOpr: 1, //1 添加修改  2 查看  3审核
      goodsArr: [],
      idAndNumberArr: [],
      docStageArr: [
        {label: '编制中', value: 0},
        {label: '编制完', value: 1},
        {label: '执行中', value: 2}
      ],
      approvalResultArr: [
        {label: '待审核', value: 0},
        {label: '审核不通过', value: 1},
        {label: '审核通过', value: 2},
      ],
      isEffectArr: [
        {label: '否', value: 0},
        {label: '是', value: 1},
      ],
      isSearchMore: false,
      activeName: 'second',
      isMore: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购申请表格数据
      buyReqList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否弹出用户选择层
      userDialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        reqUserId: null,
        reqDate: null,
        docStage: null,
        approvalResult: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
        createBy: null,
        createDate: null,
        modifyBy: null,
        modifyDate: null,
        isDel: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          {required: true, message: "单据编号不能为空", trigger: "blur"}
        ],
        reqUserId: [
          {required: true, message: "需求人不能为空", trigger: "blur"}
        ],
        reqDate: [
          {required: true, message: "需求日期不能为空", trigger: "blur"}
        ],
        createBy: [
          {required: true, message: "创建人不能为空", trigger: "blur"}
        ],
      },
      compSelectUser: null,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleShenghe(row){
        this.reset();
        this.formOpr = 3;
        const id = row.id || this.ids
        getBuyReqPlus(id).then(response => {
          this.form = response.data.buyReqDataBase;
          this.goodsArr = response.data.goodsList;
          this.idAndNumberArr = response.data.idAndNumberList;
          console.log('getBuyReqPlus',response.data)
          this.open = true;
          this.title = "采购申请-审核";
        });
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    changeHandleGoods(goodsArr) {
      console.log('changeHandleGoods goodsArr')
      console.log(goodsArr);
      this.goodsArr = goodsArr;
    },
    changeHandleUser(user) {
      console.log('changeHandleUser user')
      console.log(user);
      this.compSelectUser = user;
      this.form.reqUserId = user.userId
      this.form.reqUserName = user.nickName
      this.form.reqUserDept = user.dept.deptName
      // this.form.code = 'CGSQ-'+uuidv4()

    },
    /** 查询采购申请列表 */
    getList() {
      this.loading = true;
      listBuyReq(this.queryParams).then(response => {
        this.buyReqList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        reqUserId: null,
        reqUserName: null,
        reqDate: null,
        docStage: null,
        approvalResult: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
        createBy: null,
        createDate: null,
        modifyBy: null,
        modifyDate: null,
        isDel: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.formOpr = 1;
      this.open = true;
      this.form.code = 'CGSQ-' + Date.now()
      this.title = "添加采购申请";
      this.goodsArr = [];
      this.idAndNumberArr = []
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.formOpr = 1;
      const id = row.id || this.ids
      getBuyReqPlus(id).then(response => {
        this.form = response.data.buyReqDataBase;
        this.goodsArr = response.data.goodsList;
        this.idAndNumberArr = response.data.idAndNumberList;
        console.log(response.data)
        this.open = true;
        this.title = "修改采购申请";
      });
    },
    /** 查看按钮操作*/
    handleView(row) {
      this.reset();
      this.formOpr = 2;
      const id = row.id || this.ids
      getBuyReqPlus(id).then(response => {
        this.form = response.data.buyReqDataBase;
        this.goodsArr = response.data.goodsList;
        this.idAndNumberArr = response.data.idAndNumberList;
        console.log('getBuyReqPlus',response.data)
        this.open = true;
        this.title = "查看采购申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.formOpr != 1) {
        this.open = false;
        return;
      }
      if (this.goodsArr.length == 0) {
        this.$modal.msgWarning("请添加明细");
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.modifyBy = this.$store.getters.name;
            updateBuyReqPlus({
              "buyReqDataBase": this.form,
              "idAndNumberList": this.goodsArr
            }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.createBy = this.$store.getters.name;
            // addBuyReq(this.form).then(response => {
            //   this.$modal.msgSuccess("新增成功");
            //   this.open = false;
            //   this.getList();
            // });
            if ( this.goodsArr[this.goodsArr.length -1 ].id == undefined || this.goodsArr[this.goodsArr.length -1 ].id == null){
              this.$modal.msgWarning("请选择商品");
              return;
            }
            addBuyReqPlus({
              "buyReqDataBase": this.form,
              "idAndNumberList": this.goodsArr
            }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.goodsArr = [];
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购申请编号为"' + ids + '"的数据项？').then(function () {
        return delBuyReqPlus(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('caigou/buyReq/export', {
        ...this.queryParams
      }, `buyReq_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
